---
layout: "default"
title: "Optional"
description: "Swift documentation for 'Optional': A type that can represent either a wrapped value or nil, the absence of a."
keywords: "Optional,enum,swift,documentation,flatMap,map,customMirror,debugDescription,unsafelyUnwrapped"
root: "/v3.0"
---

<div class="intro-declaration"><code class="language-swift">enum Optional&lt;Wrapped&gt;</code></div>

<div class="discussion comment">
    <p>A type that can represent either a wrapped value or <code>nil</code>, the absence of a
value.</p>

<p>You use the <code>Optional</code> type whenever you use optional values, even if you
never type the word <code>Optional</code>. Swift&#39;s type system usually shows the
wrapped type&#39;s name with a trailing question mark (<code>?</code>) instead of showing
the full type name. For example, if a variable has the type <code>Int?</code>, that&#39;s
just another way of writing <code>Optional&lt;Int&gt;</code>. The shortened form is
preferred for ease of reading and writing code.</p>

<p>The types of <code>shortForm</code> and <code>longForm</code> in the following code sample are
the same:</p>

<pre><code class="language-swift">let shortForm: Int? = Int(&quot;42&quot;)
let longForm: Optional&lt;Int&gt; = Int(&quot;42&quot;)</code></pre>

<p>The <code>Optional</code> type is an enumeration with two cases. <code>Optional.none</code> is
equivalent to the <code>nil</code> literal. <code>Optional.some(Wrapped)</code> stores a wrapped
value. For example:</p>

<pre><code class="language-swift">let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
print(noNumber == nil)
// Prints &quot;true&quot;</code></pre>

<p>You must unwrap the value of an <code>Optional</code> instance before you can use it
in many contexts. Because Swift provides several ways to safely unwrap
optional values, you can choose the one that helps you write clear,
concise code.</p>

<p>The following examples use this dictionary of image names and file paths:</p>

<pre><code class="language-swift">let imagePaths = [&quot;star&quot;: &quot;/glyphs/star.png&quot;,
                  &quot;portrait&quot;: &quot;/images/content/portrait.jpg&quot;,
                  &quot;spacer&quot;: &quot;/images/shared/spacer.gif&quot;]</code></pre>

<p>Getting a dictionary&#39;s value using a key returns an optional value, so
<code>imagePaths[&quot;star&quot;]</code> has type <code>Optional&lt;String&gt;</code> or, written in the
preferred manner, <code>String?</code>.</p>

<h2>Optional Binding</h2>

<p>To conditionally bind the wrapped value of an <code>Optional</code> instance to a new
variable, use one of the optional binding control structures, including
<code>if let</code>, <code>guard let</code>, and <code>switch</code>.</p>

<pre><code class="language-swift">if let starPath = imagePaths[&quot;star&quot;] {
    print(&quot;The star image is at &#39;\(starPath)&#39;&quot;)
} else {
    print(&quot;Couldn&#39;t find the star image&quot;)
}
// Prints &quot;The star image is at &#39;/glyphs/star.png&#39;&quot;</code></pre>

<h2>Optional Chaining</h2>

<p>To safely access the properties and methods of a wrapped instance, use the
postfix optional chaining operator (<code>?</code>). The following example uses
optional chaining to access the <code>hasSuffix(_:)</code> method on a <code>String?</code>
instance.</p>

<pre><code class="language-swift">if let isPNG = imagePaths[&quot;star&quot;]?.hasSuffix(&quot;.png&quot;) {
    print(&quot;The star image is in PNG format&quot;)
}
// Prints &quot;The star image is in PNG format&quot;</code></pre>

<h2>Using the Nil-Coalescing Operator</h2>

<p>Use the nil-coalescing operator (<code>??</code>) to supply a default value in case
the <code>Optional</code> instance is <code>nil</code>. Here a default path is supplied for an
image that is missing from <code>imagePaths</code>.</p>

<pre><code class="language-swift">let defaultImagePath = &quot;/images/default.png&quot;
let heartPath = imagePaths[&quot;heart&quot;] ?? defaultImagePath
print(heartPath)
// Prints &quot;/images/default.png&quot;</code></pre>

<p>The <code>??</code> operator also works with another <code>Optional</code> instance on the
right-hand side. As a result, you can chain multiple <code>??</code> operators
together.</p>

<pre><code class="language-swift">let shapePath = imagePaths[&quot;cir&quot;] ?? imagePaths[&quot;squ&quot;] ?? defaultImagePath
print(shapePath)
// Prints &quot;/images/default.png&quot;</code></pre>

<h2>Unconditional Unwrapping</h2>

<p>When you&#39;re certain that an instance of <code>Optional</code> contains a value, you
can unconditionally unwrap the value by using the forced
unwrap operator (postfix <code>!</code>). For example, the result of the failable <code>Int</code>
initializer is unconditionally unwrapped in the example below.</p>

<pre><code class="language-swift">let number = Int(&quot;42&quot;)!
print(number)
// Prints &quot;42&quot;</code></pre>

<p>You can also perform unconditional optional chaining by using the postfix
<code>!</code> operator.</p>

<pre><code class="language-swift">let isPNG = imagePaths[&quot;star&quot;]!.hasSuffix(&quot;.png&quot;)
print(isPNG)
// Prints &quot;true&quot;</code></pre>

<p>Unconditionally unwrapping a <code>nil</code> instance with <code>!</code> triggers a runtime
error.</p>
</div>

<table class="standard">
<tr>
<th id="inheritance">Inheritance</th>
<td>
<code class="inherits">CustomDebugStringConvertible, CustomReflectable, ExpressibleByNilLiteral</code>
<span class="viz"><a href="hierarchy/">View Protocol Hierarchy &rarr;</a></span>
</td>
</tr>



<tr>
<th>Import</th>
<td><code class="language-swift">import Swift</code></td>
</tr>

</table>

<h3 id="cases">Cases</h3>
<div class="declaration" id="case-none">
<a class="toggle-link" data-toggle="collapse" href="#comment-case-none">case none</a>
<div class="comment collapse" id="comment-case-none"><div class="p">
    <p>The absence of a value.</p>

<p>In code, the absence of a value is typically written using the <code>nil</code>
literal rather than the explicit <code>.none</code> enumeration case.</p>

    <h4>Declaration</h4>    
    <code class="language-swift"></code>
</div></div>
</div>
<div class="declaration" id="case-some">
<a class="toggle-link" data-toggle="collapse" href="#comment-case-some">case some(Wrapped)</a>
<div class="comment collapse" id="comment-case-some"><div class="p">
    <p>The presence of a value, stored as <code>Wrapped</code>.</p>

    <h4>Declaration</h4>    
    <code class="language-swift"></code>
</div></div>
</div>

<h3>Initializers</h3>
<div class="declaration" id="init_">
<a class="toggle-link" data-toggle="collapse" href="#comment-init_">init(<wbr>_:)</a><div class="comment collapse" id="comment-init_"><div class="p">
    <p>Creates an instance that stores the given value.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">init(_ some: Wrapped)</code>

    </div></div>
</div>
<div class="declaration" id="init-nilliteral_">
<a class="toggle-link" data-toggle="collapse" href="#comment-init-nilliteral_">init(<wbr>nilLiteral:)</a><div class="comment collapse" id="comment-init-nilliteral_"><div class="p">
    <p>Creates an instance initialized with <code>nil</code>.</p>

<p>Do not call this initializer directly. It is used by the compiler when you
initialize an <code>Optional</code> instance with a <code>nil</code> literal. For example:</p>

<pre><code class="language-swift">var i: Index? = nil</code></pre>

<p>In this example, the assignment to the <code>i</code> variable calls this
initializer behind the scenes.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">init(nilLiteral: ())</code>

    </div></div>
</div>


<h3>Instance Variables</h3>
<div class="declaration" id="var-custommirror_-mirror">
<a class="toggle-link" data-toggle="collapse" href="#comment-var-custommirror_-mirror">var customMirror: Mirror</a><div class="comment collapse" id="comment-var-custommirror_-mirror"><div class="p">
    <p>The custom mirror for this instance.</p>

<p>If this type has value semantics, the mirror should be unaffected by
subsequent mutations of the instance.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">var customMirror: Mirror { get }</code>

    </div></div>
</div>
<div class="declaration" id="var-debugdescription_-string">
<a class="toggle-link" data-toggle="collapse" href="#comment-var-debugdescription_-string">var debugDescription: String</a><div class="comment collapse" id="comment-var-debugdescription_-string"><div class="p">
    <p>A textual representation of this instance, suitable for debugging.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">var debugDescription: String { get }</code>

    </div></div>
</div>
<div class="declaration" id="var-unsafelyunwrapped_-wrapped">
<a class="toggle-link" data-toggle="collapse" href="#comment-var-unsafelyunwrapped_-wrapped">var unsafelyUnwrapped: Wrapped</a><div class="comment collapse" id="comment-var-unsafelyunwrapped_-wrapped"><div class="p">
    <p>The wrapped value of this instance, unwrapped without checking whether
the instance is <code>nil</code>.</p>

<p>The <code>unsafelyUnwrapped</code> property provides the same value as the forced
unwrap operator (postfix <code>!</code>). However, in optimized builds (<code>-O</code>), no
check is performed to ensure that the current instance actually has a
value. Accessing this property in the case of a <code>nil</code> value is a serious
programming error and could lead to undefined behavior or a runtime
error.</p>

<p>In debug builds (<code>-Onone</code>), the <code>unsafelyUnwrapped</code> property has the same
behavior as using the postfix <code>!</code> operator and triggers a runtime error
if the instance is <code>nil</code>.</p>

<p>The <code>unsafelyUnwrapped</code> property is recommended over calling the
<code>unsafeBitCast(_:)</code> function because the property is more restrictive
and because accessing the property still performs checking in debug
builds.</p>

<p><strong>Warning:</strong> This property trades safety for performance.  Use
  <code>unsafelyUnwrapped</code> only when you are confident that this instance
  will never be equal to <code>nil</code> and only after you&#39;ve tried using the
  postfix <code>!</code> operator.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">var unsafelyUnwrapped: Wrapped { get }</code>

    </div></div>
</div>



<h3>Instance Methods</h3>
<div class="declaration" id="func-flatmap_">
<a class="toggle-link" data-toggle="collapse" href="#comment-func-flatmap_">func flatMap(<wbr>_:)</a>
        
<div class="comment collapse" id="comment-func-flatmap_"><div class="p">
    <p>Evaluates the given closure when this <code>Optional</code> instance is not <code>nil</code>,
passing the unwrapped value as a parameter.</p>

<p>Use the <code>flatMap</code> method with a closure that returns an optional value.
This example performs an arithmetic operation with an optional result on
an optional integer.</p>

<pre><code class="language-swift">let possibleNumber: Int? = Int(&quot;42&quot;)
let nonOverflowingSquare = possibleNumber.flatMap { x -&gt; Int? in
    let (result, overflowed) = Int.multiplyWithOverflow(x, x)
    return overflowed ? nil : result
}
print(nonOverflowingSquare)
// Prints &quot;Optional(1746)&quot;</code></pre>

<p><strong><code>transform</code>:</strong>  A closure that takes the unwrapped value
  of the instance.<br/><strong>Returns:</strong> The result of the given closure. If this instance is <code>nil</code>,
  returns <code>nil</code>.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">func flatMap&lt;U&gt;(_ transform: (Wrapped) throws -&gt; U?) rethrows -&gt; U?</code>
    
    
</div></div>
</div>
<div class="declaration" id="func-map_">
<a class="toggle-link" data-toggle="collapse" href="#comment-func-map_">func map(<wbr>_:)</a>
        
<div class="comment collapse" id="comment-func-map_"><div class="p">
    <p>Evaluates the given closure when this <code>Optional</code> instance is not <code>nil</code>,
passing the unwrapped value as a parameter.</p>

<p>Use the <code>map</code> method with a closure that returns a nonoptional value.
This example performs an arithmetic operation on an
optional integer.</p>

<pre><code class="language-swift">let possibleNumber: Int? = Int(&quot;42&quot;)
let possibleSquare = possibleNumber.map { $0 * $0 }
print(possibleSquare)
// Prints &quot;Optional(1746)&quot;

let noNumber: Int? = nil
let noSquare = noNumber.map { $0 * $0 }
print(noSquare)
// Prints &quot;nil&quot;</code></pre>

<p><strong><code>transform</code>:</strong>  A closure that takes the unwrapped value
  of the instance.
<strong>Returns:</strong> The result of the given closure. If this instance is <code>nil</code>,
  returns <code>nil</code>.</p>

    <h4>Declaration</h4>    
    <code class="language-swift">func map&lt;U&gt;(_ transform: (Wrapped) throws -&gt; U) rethrows -&gt; U?</code>
    
    
</div></div>
</div>


